﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace TextApi.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ImgController : ControllerBase
    {
        [HttpPost]
        public IActionResult Img(IFormFile file)
        {
            try
            {
                //1.判断图片的格式
                var t = file.ContentType;
                var ts = new List<string>
                {
                    "image/jpeg",
                    "image/jpg",
                    "image/png",
                    "image/jif",
                    "image/webp",
                };
                if(!ts.Contains(t))
                {
                    return Ok("不是图片");
                }
                //2.判断图片的大小
                var max = 1024 * 1024 * 2;
                if(file.Length>max)
                {
                    return Ok("大于2M");
                }
                //3.上传图片
                string p = Directory.GetCurrentDirectory() +@"/wwwroot/Img/"+ file.FileName;
                using(FileStream fs=new FileStream(p,FileMode.Create))
                {
                    file.CopyTo(fs);
                    fs.Close();
                }
                return Ok("https://localhost:7155/Img/"+file.FileName);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
